<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Customer;
use app\common\model\PaymentRecord;
use app\admin\model\User;
use app\common\model\Role;
use think\Db;
use app\common\model\Department;

/**
 * 首页接口
 */
class Finance extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    public function initData()
    {
        $user_id=$this->auth->id;

     
        $user=new User();
        $role_id=$user->where('id',$user_id)->value('role_id');

        $role=new Role();
        $department_id=$user->where('id',$user_id)->value('department_id');
        $departmentUserIds=[];
        $role_name=$role->where('id',$role_id)->value('name');
        $allow_department=0;
        $allow_staff=0;
        if($role_name=='联营商负责人'){
           $allow_staff=1;
           $department_id=$user->where('id',$user_id)->value('department_id');
           $departmentUserIds = $this->getDepartmentUserIds($department_id);
        }elseif(in_array($role_name,['项目负责人','管理员','业务经理','财务'])){
            $allow_department=1;
            $allow_staff=1;
            $department_id=1;
            $departmentUserIds = $this->getDepartmentUserIds($department_id);
        }else{
            $departmentUserIds[]=$user_id;
        }

    

        $info=$this->yibiaopanData($departmentUserIds,$department_id);


        $data['staff_id']=$user_id;
        $data['department_id']=$department_id;
        $data['allow_department']=$allow_department;
        $data['allow_staff']=$allow_staff;
        $data['info']=$info;
        $this->success('请求成功', $data);
     }

    public function yibiaopanData($departmentUserIds,$department_id){

        
        $data=[];
        //堡垒总资产
        $customer= new Customer();
        $customerQuery = $customer::where('is_claim', 1)->where('is_delete', 0);
        if($department_id!=1){
             $customerQuery = $customerQuery->where('staff_id', 'in', $departmentUserIds);
        }

    
        $totalAmount_data = $customerQuery
            ->field("SUM(CASE 
        WHEN remainingPrincipal > 0 AND (compensationAmount IS NULL OR compensationAmount = 0) THEN remainingPrincipal
        WHEN compensationAmount > 0 AND (remainingPrincipal IS NULL OR remainingPrincipal = 0) THEN compensationAmount
        WHEN remainingPrincipal > 0 AND compensationAmount > 0 THEN remainingPrincipal
        ELSE 0
    END) AS totalAmount")
            ->find();

        $totalAmount=$totalAmount_data['totalAmount'];
        $data['totalAmount'] = $totalAmount??0;

        //回款总金额start
        $paymentRecord= new PaymentRecord();
        $paymentQuery = $paymentRecord::where('is_delete', 0);
        $where=[];
        $where['a.is_delete']=0;

        if($department_id!=1){
            $where['a.staff_id'] = ['in', $departmentUserIds];
        }
        $contractids=Db::name('contracts a')
        ->join('customer c', 'a.customer_id = c.id', 'LEFT')
        ->join('user u', 'a.staff_id = u.id', 'LEFT')
        ->join('user us', 'a.user_id = us.id', 'LEFT')
        ->field('sum(a.amount) as total')
        ->where($where)
        ->column('a.id');
      
        $paymentAmount_data = $paymentQuery
            ->where('contract_id','in',$contractids)
            ->field("sum(amount) as paymentAmount")
            ->find();
        $paymentAmount=$paymentAmount_data['paymentAmount'];
        $data['paymentAmount'] =$paymentAmount??0;
//        回款总金额end


//        待回款总额
        $lackAmount=$totalAmount-$paymentAmount;
        $data['lackAmount'] = $lackAmount;


//        待回款总额比例
        $lackPercent = $totalAmount > 0 ? round(($lackAmount / $totalAmount) * 100, 2) : 0;
        $data['lackPercent'] = $lackPercent;

//        案源总数
        $customerTotalQuery = $customer->where('is_claim', 1)->where('is_delete', 0);
        if($department_id!=1){
            $customerTotalQuery = $customerTotalQuery->where('staff_id', 'in', $departmentUserIds);
        }   
        $customerTotal = $customerTotalQuery->count();
        $data['customerTotal'] = $customerTotal;

//        立案总数
        $filingQuery = $customer->where(function($query){
            $query->where('filingTime', 'neq', '')
                ->whereOr('mailDate', 'neq', '')
                ->whereOr('filingCaseNo', 'neq', '')
                ->whereOr('court', 'neq', '')
                ->whereOr('courtPhone', 'neq', '')
                ->whereOr('executionCaseNo', 'neq', '');
        })->where('is_delete', 0);

        if($department_id!=1){
            $filingQuery = $filingQuery->where('staff_id', 'in', $departmentUserIds);
        }
        $filingCount = $filingQuery->count();
        $data['filingCount'] = $filingCount;
        return $data;
    }

    public function yibiaopan(){
        $department_id = $this->request->post('department_id', 2);
        $staff_id = $this->request->post('staff_id', '');

        if($department_id){
            $departmentUserIds = $this->getDepartmentUserIds($department_id);
        }

        if($staff_id){
            $departmentUserIds=[];
            $department_id=2;
            $departmentUserIds[]=$staff_id;
        }
        $data=$this->yibiaopanData($departmentUserIds,$department_id);
        $this->success('请求成功', $data);
    }
    /**
     * 递归获取所有子部门ID
     * @param int $parentId 父部门ID
     * @return array 子部门ID数组
     */
    private function getChildDepartmentIds($parentId)
    {
        $ids = [];
        $departments = Department::where('parent_id', $parentId)
            ->where('status', 1)
            ->where('is_delete', 0)
            ->select();
            
        foreach ($departments as $department) {
            $ids[] = $department['id'];
            // 递归获取子部门的子部门
            $childIds = $this->getChildDepartmentIds($department['id']);
            $ids = array_merge($ids, $childIds);
        }
        
        return $ids;
    }

    public function getStaffList()
    {
        $department_id = $this->request->post('department_id', '');
        $name = $this->request->post('name', '');
     
        // 查询条件
        $where = [];
        
        // 处理部门ID，获取所有子部门ID
        if ($department_id) {
            // 获取所有子部门ID
            $departmentIds = $this->getChildDepartmentIds($department_id);
            // 将当前部门ID也加入数组
            $departmentIds[] = $department_id;
            $where['u.department_id'] = ['in', $departmentIds];
        }
        

    
        if ($name) {
            $where['u.name'] = ['like','%'.$name.'%'];
        }
        
        // 基础条件：用户未删除
        $baseWhere = ['u.is_delete' => 0];

        // 查询列表数据
        $list = Db::name('user u')
            ->join('role r', 'u.role_id = r.id', 'left')
            ->join('department d', 'u.department_id = d.id', 'left')
            ->field('u.*, r.name as role_name, d.title as department_name')
            ->where($baseWhere)
            ->where($where)
            ->order('u.id', 'desc')
            ->select();

        $this->success('请求成功', ['list' => $list]);
    }


    
    /**
     * 首页
     *
     */

    public function getOrderList()
    {
        // 如果是 Selectpage 请求
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }

        // 获取分页参数
        $page = $this->request->post('page', 1);
        $pageSize = $this->request->post('pageSize', 10);

        // 查询条件
        $where = [];
        $searchKey = $this->request->post('searchKey', '');
        if ($searchKey) {
            $where['name|customer_name|phone|manager'] = ['like', "%{$searchKey}%"];
        }

        $orders = new \app\common\model\Orders();
        $total = $orders->where($where)->count();
        $list = $orders
            ->where($where)
            ->order('id', 'desc')
            ->page($page, $pageSize)
            ->select();

        $this->success('请求成功', ['list' => $list, 'total' => $total]);
    }

    public function getAccountList()
    {
        $page = $this->request->post('page', 1);
        $pageSize = $this->request->post('pageSize', 20);
        $searchKey = $this->request->post('searchKey', '');

        $where = ['is_delete' => 0];
        if ($searchKey) {
            $where['bank|account_name|account_no'] = ['like', "%{$searchKey}%"];
        }

        $accountModel = new \app\common\model\Account();
        $total = $accountModel->where($where)->count();
        $list = $accountModel
            ->where($where)
            ->order('id', 'desc')
            ->page($page, $pageSize)
            ->select();

        $this->success('请求成功', ['list' => $list, 'total' => $total]);
    }

    public function saveAccount()
    {
        $params = $this->request->post();

        if (empty($params)) {
            $this->error('参数不能为空');
        }

        $params['updatetime'] = date('Y-m-d H:i:s');
        if (empty($params['id'])) {
            $params['createtime'] = date('Y-m-d H:i:s');
        }

        $accountModel = new \app\common\model\Account();

        if (!empty($params['id'])) {
            $result = $accountModel->where('id', $params['id'])->update($params);
        } else {
            $result = $accountModel->insert($params);
        }

        if ($result !== false) {
            $this->success('保存成功');
        } else {
            $this->error('保存失败');
        }

    }

    public function deleteAccount()
    {
        $ids = $this->request->post('ids', '');
        $ids = explode(',', $ids);
        $accountModel = new \app\common\model\Account();
        $accountModel->whereIn('id', $ids)->update(['is_delete' => 1, 'updatetime' => date('Y-m-d H:i:s')]);
        $this->success('删除成功');
    }



}


